package koalacam.local;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 网络开关
 * @author Wangshutao
 * 2016年11月9日
 */
public class NetLockerController {

	private static final String COMMAND_OPEN = "on1";

	private static final String COMMAND_CLOSE = "off1";

	private static final int PORT = 5000;

	private DatagramSocket socket;

	private ExecutorService executorService = Executors.newCachedThreadPool();

	synchronized public void init() {
		try {
			socket = new DatagramSocket();
			socket.setSoTimeout(6000);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	public void openDoor(final String lockerAddress) {
		new Thread() {
			public void run() {
				openDoorCommand(lockerAddress);
				try {
					sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				closeDoorCommand(lockerAddress);
			}
		}.start();

	}

	synchronized public void openDoorCommand(String lockerAddress) {
		sendCommand(lockerAddress, COMMAND_OPEN);
	}

	synchronized public void closeDoorCommand(String lockerAddress) {
		sendCommand(lockerAddress, COMMAND_CLOSE);
	}

	synchronized private void sendCommand(final String lockerAddress, final String command) {
		executorService.submit(new Runnable() {
			public void run() {
				try {
					InetAddress serverAddress = InetAddress.getByName(lockerAddress);
					byte[] data = command.getBytes();
					DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, PORT);
					socket.send(packet);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	synchronized public void release() {
		if (socket != null) {
			try {
				socket.close();
			} catch (Exception e) {

			}
		}
		socket = null;
	}

	public static void main(String[] args) {
		NetLockerController doorController = new NetLockerController();
		doorController.init();
		doorController.openDoor("192.168.0.105");
	}

}
